package com.springboot.datasource;

import com.springboot.datasource.config.DynamicDataSource;
import com.springboot.datasource.interfaces.DataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @description:
 * @author: zyj
 * @create: 2020-08-18 14:53
 **/
@Component
@Aspect
@Slf4j
public class DataSourceAspect {



    @Pointcut("@within(com.springboot.datasource.interfaces.DataSource) || @annotation(com.springboot.datasource.interfaces.DataSource)")
    public void pointCut(){
    }

    @Before("pointCut()")
    public void doBefore(JoinPoint point){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String tenant = request.getHeader("tenant");
        if(!StringUtils.isEmpty(tenant) ){
            DataSourceContextHolder.setDataSource(tenant);
        }

    }

    @After("pointCut()")
    public void doAfter(){
        DataSourceContextHolder.clear();
    }
}
